<template>
  <div>
    <el-button :disabled="disabled" type="primary" plain icon="el-icon-printer" size="mini"
      @click="printClick" v-if="showPrintBtn">打印</el-button>
    <button v-print="print" ref="printButton" style="display: none;"></button>
    <div :class="show ? '' : 'hidden'">
      <div :id="id" style="display: flex;flex-direction: column;align-items: center;">
        <div v-if="title" style="margin-bottom: 3mm;font-size: 6mm;font-weight: bold;">{{ title }}</div>
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'print',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: 'print-content'
    },
    title: {
      type: String,
      default: ''
    },
    beforeMethod: {
      type: Function,
      default: function () { }
    },
    show: {
      type: Boolean,
      default: false
    },
    autoPrint: {
      type: Boolean,
      default: true
    },
    showPrintBtn: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      print: {
        id: this.id,
        popTitle: '', // 打印配置页上方的标题
        extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        preview: false, // 是否启动预览模式，默认是false
        previewTitle: '预览的标题', // 打印预览的标题
        previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        previewBeforeOpenCallback() { console.log('正在加载预览窗口！') }, // 预览窗口打开之前的callback
        previewOpenCallback() { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
        beforeOpenCallback() { console.log('开始打印之前！') }, // 开始打印之前的callback
        openCallback() { console.log('执行打印了！') }, // 调用打印时的callback
        closeCallback() { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted() { console.log('点击v-print绑定的按钮了！') },
        standard: '',
        extarCss: ''
      }
    }
  },
  methods: {
    async printClick() {
      await this.beforeMethod();
      this.autoPrint && this.printPreview()
    },
    printPreview() {
      this.$refs.printButton.click()
    }
  }
}
</script>

<style>
@page {
  size: auto;
  margin: 3mm;
}

.hidden {
  width: 0;
  height: 0;
  overflow: hidden;
}
</style>
